import React, { useEffect, useState } from 'react'
import { createForm } from '@formily/core'
import { createSchemaField } from '@formily/react'
import { Form, FormItem, FormLayout, Switch } from '@formily/antd'
import style from './index.less'
import { Button, Input } from 'antd'
import ZB from './component'
import json from './schema.json'
import * as ICONS from '@ant-design/icons'

export default () => {
  const normalForm = createForm({
    validateFirst: true,
  })

  const SchemaField = createSchemaField({
    components: {
      FormItem,
      Input,
      FormLayout,
      ZB,
      Switch
    },
    scope: {
      ...{
        icon(name: string) {
          return React.createElement(ICONS[name])
        },
        customMethod: async (field: any) => {
          console.log('自定义方法', field)
          return field
        },
      },
    },
  })

  const save = () => {
    normalForm.submit((values) => {
      console.log('values', JSON.stringify(values))
    })
  }

  const [schemaForm, setSchemaForm] = useState<any>({})
  useEffect(() => {
    setSchemaForm(json)
  }, [])
  return (
    <div className={style.schemaForm}>
      <Form
        form={normalForm}
      >
        <SchemaField schema={schemaForm} />
        <FormItem>
          <Button type="primary" onClick={save}>确定</Button>
        </FormItem>
      </Form>
    </div>
  )
}